<template>
  <div class="login-logo">
    <div class="wrapper">
      <!-- 登录模式切换 Tab -->
      <div class="tab-container">
        <div
          :class="['tab-item', { active: loginMode === 'account' }]"
          @click="loginMode = 'account'"
        >
          账号密码登录
        </div>
        <div
          :class="['tab-item', { active: loginMode === 'telphone' }]"
          @click="loginMode = 'telphone'"
        >
          手机号登录
        </div>
      </div>

      <!-- 账号密码登录 -->
      <div v-if="loginMode === 'account'">
        <h1>登录</h1>
        <div class="input-box">
          <i class="fas fa-envelope icon"></i>
          <input v-model="teacherName" type="username" required placeholder="账户名" />
        </div>
        <div class="input-box">
          <i class="fas fa-lock icon"></i>
          <input v-model="password" type="password" required placeholder="密码" />
        </div>

        <div class="row">
          <a>忘记密码</a>
        </div>

        <button @click="handleAccountLogin" class="btn">登录</button>
      </div>

      <!-- 手机号登录 -->
      <div v-else>
        <h1>手机号登录</h1>
        <div class="input-box">
          <i class="fas fa-phone icon"></i>
          <input v-model="telephone" type="number" required placeholder="手机号" />
        </div>
        <div class="input-box code-row">
          <i class="fas fa-code icon"></i>
          <input v-model="code" type="number" required placeholder="验证码" />
          <button class="send-code-btn" :disabled="isSmsCodeLoading" @click="sendSmsCode">
            {{ smsCodeText }}
          </button>
        </div>

        <button @click="handlePhoneLogin" class="btn">登录</button>
      </div>

      <div class="signup-link">
        <p>没有账号 <a href="#" @click="register">点击这里</a></p>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import api from '@/api/userLogin'
import log from '@/api/log'
import { ref, onMounted } from 'vue'
import router from '@/router'
import { TeacherInfo } from '@/stores/counter'
import { ElMessage } from 'element-plus' // 引入 Element Plus 的消息提示
import { onUnmounted } from 'vue'


const userStore = TeacherInfo()
const loginMode = ref<'account' | 'telphone'>('account') // 登录模式：account/phone

// 账号密码登录字段
const teacherName = ref('')
const password = ref('')

// 手机号登录字段
const telephone = ref('')
const code = ref('')
const smsCodeText = ref('发送验证码')
const isSmsCodeLoading = ref(false)
let smsTimer: number | undefined

// 身份字段
const role = ref('')

// 切换注册页
const register = () => {
  router.push('/register')
}

// 账号密码登录逻辑
const handleAccountLogin = () => {
  if (!teacherName.value || !password.value) {
    ElMessage.warning('请填写账户名和密码')
    return
  }
  api
    .login({ teacherName: teacherName.value, password: password.value })
    .then((res) => {
      if (res.code == 200) {
        ElMessage.success('登录成功')
        getRoleByTeacherName()
        router.push('back')
      }
    })
    .catch((error: any) => {
      ElMessage.error('登录失败：' + error.message)
    })
}

// 手机号登录 - 发送验证码
const sendSmsCode = async () => {
  if (!telephone.value || !/^1\d{10}$/.test(telephone.value)) {
    ElMessage.warning('请输入正确的手机号')
    return
  }
  isSmsCodeLoading.value = true
  smsCodeText.value = '发送中...'
  try {
  const res = await api.phoneLogin({ 
    telephone: telephone.value, 
    code: code.value 
  });
  // 假设 ResponseEntity 有 data 包含 code，按需调整
  if (res.code === 200) { 
    ElMessage.success('验证码发送成功');
  } else {
    throw new Error('验证码发送失败');
  }
} catch (error) {
  console.error('操作失败:', error);
  ElMessage.error('验证码发送失败');
}
}

// 手机号登录 - 登录逻辑
const handlePhoneLogin = () => {
  if (!telephone.value || !code.value) {
    ElMessage.warning('请填写手机号和验证码')
    return
  }
  // 模拟接口请求（实际替换为真实接口）
  api
    .checkCode({ telephone: telephone.value, code: code.value })
    .then(() => {
      getRoleByTelePhone()
      ElMessage.success('登录成功')
      router.push('back')
    })
    .catch(() => {
      ElMessage.error('登录失败')
    })
}
//用户名密码登录--获取身份
async function getRoleByTeacherName() {
  try {
    // 等待Promise完成，确保role.value被正确赋值
    const res = await log.findTeacherRoleByTeacherName({
      teacherName: teacherName.value
    });
    role.value = res.data as string;

    // 此时role.value已经有值，可以安全地调用addLog
    log.addLog({
      loginName: teacherName.value,
      role: role.value,
    });
  } catch (error) {
    console.error('获取角色失败:', error);
  }
}


//手机号码登录--获取身份
async function getRoleByTelePhone() {
  try {
    // 等待Promise完成，确保role.value被正确赋值
    const logrole = await log.findTeacherRoleByTelephone({
      telephone: telephone.value
    });
    // 等待Promise完成，确保role.value被正确赋值
    const logname = await log.findTeacherRoleByTelephone({
      telephone: telephone.value
    });
    role.value = logrole.data as string;
    teacherName.value = logname.data as string

    // 此时role.value已经有值，可以安全地调用addLog
    log.addLog({
      loginName: teacherName.value,
      role: role.value,
    });
  } catch (error) {
    console.error('获取角色失败:', error);
  }
}

// 组件销毁时清除定时器
onUnmounted(() => {
  if (smsTimer) clearInterval(smsTimer)
})
</script>

<style scoped>
.login-logo {
  width: 100%;
  height: 98vh;
  display: flex;
  background-color: #ff000063;
}

/* 通用样式 */
* {
  font-family: 'Poppins', sans-serif;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-image: url('../../assets/bg1.jpg');
  background-size: 100%;
  background-position: center;
}

.wrapper {
  position: relative;
  width: 700px;
  height: 500px; /* 增加高度适配手机号登录 */
  border: 2px solid rgba(255, 255, 255, 0.5);
  border-radius: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(15px);
  margin: auto;
  padding: 20px;
}

.wrapper:hover {
  box-shadow: 0 0 40px rgba(255, 255, 255, 0.5);
  background: #46474e14;
}

.wrapper h1 {
  font-size: 2em;
  color: #fff;
  text-align: center;
  margin-bottom: 20px;
}

/* Tab 切换样式 */
.tab-container {
  display: flex;
  margin-bottom: 20px;
}

.tab-item {
  padding: 10px 20px;
  color: #fff;
  cursor: pointer;
  border: 1px solid rgba(255, 255, 255, 0.5);
  border-radius: 20px;
  margin: 0 10px;
  transition: all 0.3s ease;
}

.tab-item.active {
  background: #fff;
  color: #000;
  border: 1px solid #fff;
}

/* 输入框样式 */
.input-box {
  position: relative;
  width: 310px;
  margin: 20px 0;
  border-bottom: 2px solid #fff;
}

.input-box input {
  width: 100%;
  height: 50px;
  background: transparent;
  outline: none;
  border: none;
  font-size: 1em;
  color: #fff;
  padding: 0 40px 0 5px;
}

.input-box .icon {
  position: absolute;
  right: 8px;
  color: #fff;
  font-size: 1.2em;
  line-height: 57px;
}

/* 验证码行样式 */
.code-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.send-code-btn {
  background: #fff;
  color: #000;
  border: none;
  padding: 10px 20px;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.send-code-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

/* 按钮样式 */
.btn {
  width: 100%;
  height: 40px;
  background: #fff;
  outline: none;
  border: none;
  border-radius: 40px;
  cursor: pointer;
  font-size: 1em;
  font-weight: 500;
  color: #000;
  margin-top: 10px;
  transition: all 0.3s ease;
}

.btn:hover {
  background: #ffffea;
}

/* 辅助行样式 */
.row {
  margin: -15px 0 15px;
  font-size: 0.9em;
  color: #fff;
  display: flex;
  justify-content: space-between;
}

.row a {
  color: #fff;
  text-decoration: none;
}

.row a:hover {
  text-decoration: underline;
}

/* 注册链接样式 */
.signup-link {
  font-size: 0.9em;
  color: #fff;
  text-align: center;
  margin-top: 20px;
}

.signup-link a {
  color: #fff;
  text-decoration: none;
  font-weight: 600;
}

.signup-link a:hover {
  text-decoration: underline;
}

/* 响应式适配 */
@media (max-width: 360px) {
  .wrapper {
    width: 100%;
    height: 100vh;
    border: none;
    border-radius: 0px;
  }

  .input-box {
    width: 290px;
  }
}
</style>
